package cn.edu.pku.wxlib.common.interceptor;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import cn.edu.pku.wxlib.common.authority.Login;
import cn.edu.pku.wxlib.common.authority.enums.ResultTypeEnum;
import cn.edu.pku.wxlib.vo.sessionmodel.SessionUser;

/**
 * 检查是否已经登录
 *
 */
public class LoginAnnotationInterceptor extends HandlerInterceptorAdapter {

	final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if(handler instanceof org.springframework.web.servlet.resource.ResourceHttpRequestHandler){
			// TODO 静态文件
			return true;
		}
		HandlerMethod handler2 = (HandlerMethod) handler;
		Login login = handler2.getMethodAnnotation(Login.class);

		if (null == login) {
			// 没有声明权限
			return true;
		}

		HttpSession session = request.getSession();
		SessionUser user = (SessionUser) session.getAttribute("login");

		if (null == user) {
			if (login.value() == ResultTypeEnum.page) {//页面
				String url = request.getRequestURL().toString();  //当前请求url
				
				String queryString = request.getQueryString();
				if(queryString!=null&&!("").equals(queryString))
					url = url+"?"+queryString;
				request.setAttribute("redirectUrl", java.net.URLEncoder.encode(url,"utf-8")); //url编码 登陆后跳转到该页面
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			} else if (login.value() == ResultTypeEnum.json) {//ajax
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=UTF-8");
				OutputStream out = response.getOutputStream();
				PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
				pw.println("{\"result\":false,\"resultcode\":-1,\"msg\":\"未登录\"}");
				pw.flush();
				pw.close();
			}
			return false;
		}
		return true;
	}
}
